/*
 * Copyright (C) 2006-2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.Collections;

using Gtk;

namespace DCSharp.Gui
{
	public class PopulatePopupArgs : EventArgs
	{
		private Menu menu;

		public PopulatePopupArgs(Menu menu)
		{
			this.menu = menu;
		}

		public Menu Menu
		{
			get { return menu; }
		}
	}

	public class MenuTreeView : TreeView
	{
		public event EventHandler<PopulatePopupArgs> PopulatePopup;

		public MenuTreeView(TreeModel model) : base(model)
		{
		}

		public MenuTreeView() : base()
		{
		}

		#region Methods

		protected override bool OnButtonPressEvent(Gdk.EventButton evnt)
		{
			if (evnt.Type == Gdk.EventType.ButtonPress && evnt.Button == 3)
			{
				TreePath path;
				if (GetPathAtPos((int)evnt.X, (int)evnt.Y, out path))
				{
					// TreePath.Equals is broken. Proper implementation:
					Predicate<TreePath> pathEquals = delegate(TreePath p)
					{
						return p.Compare(path) == 0;
					};

					// Selection handling
					// TODO: Proper selection when the shift key is pressed.
					TreePath[] selectedPaths = Selection.GetSelectedRows();
					if (!Array.Exists(selectedPaths, pathEquals))
					{
						// Path not selected
						if ((evnt.State & Gdk.ModifierType.ControlMask) == 0)
						{
							Selection.UnselectAll();
						}
						Selection.SelectPath(path);
					}

					DoMenuPopup(evnt);
					return true;
				}
			}
			return base.OnButtonPressEvent(evnt);
		}

		protected override bool OnPopupMenu()
		{
			DoMenuPopup(null);
			return true;
		}

		protected void DoMenuPopup(Gdk.EventButton evnt)
		{
			Menu menu = new Menu();

			OnPopulatePopup(menu);

			if (menu.Children.Length > 0)
			{
				// TODO: Position the menu when the event is null.
				uint button = evnt != null ? evnt.Button : 0;
				uint eventTime = evnt != null ? evnt.Time : Global.CurrentEventTime;

				menu.Popup(null, null, null, button, eventTime);
			}
		}

		protected virtual void OnPopulatePopup(Menu menu)
		{
			if (PopulatePopup != null)
			{
				PopulatePopup(this, new PopulatePopupArgs(menu));
			}
		}

		#endregion
	}
}
